package com.docman.controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.docman.dao.AdvancedSearchDAO;
import com.docman.domainmodel.DocumentBean;


@WebServlet("/AdvanceSearchServlet")
public class AdvanceSearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public AdvanceSearchServlet() {
        super();
        
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("text/html;  charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		
		RequestDispatcher dispatcher = null;
		boolean isNull = false;
		
		String fileName = request.getParameter("docName");
		String tag = request.getParameter("docTag");
		String uploader = request.getParameter("uploader");
		String time1 = request.getParameter("oldDate");
		String time2 = request.getParameter("newDate");
		
		//System.out.println(fileName +" "+tag +" "+ uploader +" "+ time1 + "" + time2 +"\n");
		
		if((fileName.equals("") || fileName == null) && (tag.equals("-1") || tag == null)
			&& (uploader.equals("") || uploader == null) && (time1.equals("") || time1 == null)
			&& (time2.equals("") || time2 == null)) {
			//request.setAttribute("error", "Arama yapmanız için en az bir seçenek doldurulmalıdır.");
			isNull = true;
		
		} else {
		
		if(fileName.equals("") || fileName == null){
			fileName = "";
		}
		
		if(tag.equals("-1") || tag == null){
			tag = "";
		}
		
		if(uploader.equals("") || uploader == null){
			uploader = "";
		}
		
		if(time1.equals("") || time1 == null){
			time1 = "";
		}
		
		if(time2.equals("") || time2 == null){
			time2 = "";
		}
		
		ArrayList<String> searchArray = new ArrayList<String>();
		searchArray.add(fileName);
		searchArray.add(tag);
		searchArray.add(uploader);
		searchArray.add(time1);
		searchArray.add(time2);
		
		ArrayList<DocumentBean> docs = new ArrayList<DocumentBean>();
		
		docs = AdvancedSearchDAO.search(searchArray);
		request.setAttribute("docList", docs);
		
	}
		
		if(isNull){
			
			response.sendRedirect("advanceSearch.jsp");
		} else {
			
			dispatcher = getServletContext().getRequestDispatcher("/searchResult.jsp");
		}
		if (dispatcher != null){
		  dispatcher.forward(request, response);
		}
		
	}
		

}
